/**
 *
 */
package com.darren.befriend;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;

import com.darren.befriend.R.layout;
import com.darren.befriend.utilities.LogUtil;
import com.darren.befriend.utilities.MySharedPreferences;
import com.darren.befriend.views.MyProgressDialog;
import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.model.GraphUser;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseInstallation;
import com.parse.ParseObject;
import com.parse.ParseUser;

/**
 * @author ubuntu
 * 
 */
public class LoginActivity extends BaseActivity {

	private Dialog mDialog;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.darren.befriend.BaseActivity#addContent()
	 */
	@Override
	protected int addContent() {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		return layout.layout_login;
	}

	@Override
	protected void initView() {
		super.initView();

		ImageView signInBtn = (ImageView) findViewById(R.id.signin_btn);
		signInBtn.setOnClickListener(this);

		ImageView signUpBtn = (ImageView) findViewById(R.id.signup_btn);
		signUpBtn.setOnClickListener(this);

		ImageView signInFbBtn = (ImageView) findViewById(R.id.signin_fb_btn);
		signInFbBtn.setOnClickListener(this);
	}

	@Override
	protected void onResume() {

		super.onResume();
	}

	@Override
	protected void onPause() {

		super.onPause();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onClick(View arg0) {
		int id = arg0.getId();
		switch (id) {
		case R.id.signin_btn:
			Intent intent = new Intent(this, SignInActivity.class);
			startActivity(intent);
			// finish();
			break;
		case R.id.signup_btn:
			Intent newintent = new Intent(this, SignUpActivity.class);
			startActivity(newintent);
			// finish();
			break;
		case R.id.signin_fb_btn:
			mDialog = MyProgressDialog.show(LoginActivity.this, "", "", false,
					false);
			signInWithFacebook();
			break;
		default:
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data);
	}

	/**
	 * Sign in application by facebook account
	 * */
	private void signInWithFacebook() {

		List<String> permissions = Arrays.asList("basic_info", "user_birthday",
				"email");
		ParseFacebookUtils.logIn(permissions, this, new LogInCallback() {

			@Override
			public void done(ParseUser user, ParseException arg1) {
				if (user == null) {

					LogUtil.e("signInWithFacebook",
							"Uh oh. The user cancelled the Facebook login.");
					mDialog.dismiss();
				} else if (user.isNew()) {
					LogUtil.e("signInWithFacebook",
							"User signed up and logged in through Facebook!");

					makeMeRequestForUserData();
					Intent initIntent = new Intent(LoginActivity.this,
							UserSettingInitialActivity.class);
					startActivity(initIntent);
				} else {
					LogUtil.e("signInWithFacebook",
							"User logged in through Facebook!");
					getUserInfor(user);
					Intent homeIntent = new Intent(LoginActivity.this,
							HomeActivity.class);
					homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
							| Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(homeIntent);
					finish();
				}
			}

		});

		// Dismiss dialog
		// mDialog.dismiss();
	}

	/**
	 * Get user information from server when user already sign up before
	 * */
	private void getUserInfor(final ParseUser user) {

		MySharedPreferences.setPreferences(MySharedPreferences.PREF_USERNAME,
				user.getUsername());
		@SuppressWarnings("unchecked")
		ArrayList<String> enemyArr = (ArrayList<String>) user.get("Enemy");
		if (enemyArr != null && enemyArr.size() > 0) {

			ArrayList<String> enemyArrTemp = enemyArr;
			for (int i = 0; i < enemyArrTemp.size(); i++) {

				String enemy = enemyArrTemp.get(i);
				String[] temp = enemy.split("\\$\\$\\$");
				long time = Long.parseLong(temp[1]);
				long currentTime = (long) new Date().getTime() / 1000;
				if ((currentTime - time) > 86400 * 15) {

					enemyArr.remove(i);
				}
			}

			user.put("Enemy", enemyArr);
		}

		try {
			if (user.getParseObject("Filter") != null) {

				user.put("Filter", user.getParseObject("Filter").fetch());
			}

			if (user.getParseObject("MeInfo") != null) {

				user.put("MeInfo", user.getParseObject("MeInfo").fetch());
			}

			user.put("Status", true);
			user.saveInBackground();
		} catch (ParseException e) {

			LogUtil.e("getUserInfor", e.getMessage());
		}

		// Push notification
		ParseInstallation installation = ParseInstallation
				.getCurrentInstallation();
		installation.addUnique("channels", "CH_" + user.getUsername());
		installation.saveInBackground();

		mParseUser = user;
		finish();
		try {

			mDialog.dismiss();
		} catch (Exception ex) {

			LogUtil.e("Dismis dialog ", ex.getMessage());
		}
	}

	/**
	 * Get user data from facebook
	 * 
	 * */
	private void makeMeRequestForUserData() {
		Request request = Request.newMeRequest(ParseFacebookUtils.getSession(),
				new Request.GraphUserCallback() {

					@Override
					public void onCompleted(GraphUser user, Response response) {
						// TODO Auto-generated method stub
						if (user != null) {

							final ParseUser pUser = ParseUser.getCurrentUser();
							pUser.setEmail(user.getProperty("email").toString());
							try {

								pUser.setUsername(user.getUsername());
							} catch (Exception ex) {

							}

							pUser.setPassword("kki");
							pUser.put("fullName", user.getFirstName());
							List<String> friends = new ArrayList<String>();
							pUser.put("Friends", friends);
							List<String> enemys = new ArrayList<String>();
							pUser.put("Enemy", enemys);
							int age = 17;

							// Get age
							if (user.getBirthday() != null
									&& !user.getBirthday().isEmpty()) {
								int start = user.getBirthday().lastIndexOf("/") + 1;
								int year = Integer.parseInt(user.getBirthday()
										.substring(start));
								Calendar cal = Calendar.getInstance();
								int currentYear = cal.get(Calendar.YEAR);
								age = currentYear - year;
							}

							// Create Me info
							ParseObject meInfo = new ParseObject("MeClass");
							meInfo.put("Gender", 0);
							meInfo.put("MoneyToBurn", 500);
							meInfo.put("MyAge", age);
							meInfo.put("Nationality", 0);
							meInfo.put("Religion", 0);
							meInfo.put("Personality", 0);
							meInfo.put("Children", 0);
							meInfo.put("Intelligence", 1);
							meInfo.put("University", 0);
							meInfo.put("Employer", "");
							meInfo.put("About", "");
							meInfo.put("Parent", pUser.getUsername());
							List<Boolean> selectionArray = new ArrayList<Boolean>();
							for (int i = 0; i < 9; i++) {

								selectionArray.add(false);
							}

							meInfo.put("Hobby", selectionArray);
							pUser.put("MeInfo", meInfo);

							// Create Filter Info
							ParseObject filter = new ParseObject("FilterClass");
							filter.put("Men", true);
							filter.put("Women", true);
							filter.put("Within", 25);
							filter.put("StartAge", 23);
							filter.put("EndAge", 38);
							filter.put("StartMoney", 200);
							filter.put("EndMoney", 600);
							filter.put("Parent", pUser.getUsername());
							List<Boolean> personalityArray = new ArrayList<Boolean>();
							for (int i = 0; i < 13; i++) {
								selectionArray.add(false);
							}

							filter.put("Personality", personalityArray);
							filter.put("Child", 0);
							pUser.put("Filter", filter);
							pUser.put("Status", true);

							// Push notification
							ParseInstallation installation = ParseInstallation
									.getCurrentInstallation();
							installation.addUnique("channels",
									"CH_" + pUser.getUsername());
							installation.saveInBackground();
							if (mGeoPoint != null) {

								pUser.put("Position", mGeoPoint);
							}

							mParseUser = pUser;
							try {

								LogUtil.e("Save data", "Save data when back");
								mParseUser.saveInBackground();
								ParseObject meInfo1 = mParseUser
										.getParseObject("MeInfo");
								ParseObject filter1 = mParseUser
										.getParseObject("Filter");
								meInfo1.saveInBackground();
								filter1.saveInBackground();
							} catch (Exception e) {
								// TODO Auto-generated catch block

							}

							// Save username and password to
							// shared preference
							MySharedPreferences.setPreferences(
									MySharedPreferences.PREF_USERNAME,
									pUser.getUsername());
							finish();
							mDialog.dismiss();
						} else if (response.getError() != null) {
							if ((response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_RETRY)
									|| (response.getError().getCategory() == FacebookRequestError.Category.AUTHENTICATION_REOPEN_SESSION)) {

								LogUtil.e("makeMeRequestForUserData",
										"The facebook session was invalidated.");
							} else {

								LogUtil.e("makeMeRequestForUserData",
										"Some other error: "
												+ response.getError()
														.getErrorMessage());
							}

							// Request data again like iOS flow
							makeMeRequestForUserData();
						}
					}
				});

		request.executeAsync();
	}
}
